﻿using System;
using System.Web.Mvc;
using Books.Interfaces;
using Books.Web.ViewModels;
using RefLib.Branding.MVC;
using RefLib.MVC.JsonModels;

namespace Books.Web.Controllers
{
    public class PublisherController : BrandingController
    {
        public PublisherController(IPublisherApp publisherApp)
        {
            if (publisherApp == null)
                throw new Exception("IPublisherApp is null");
            _publisherApp = publisherApp;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult PublisherDelete(int id)
        {
            _publisherApp.DeletePublisher(id);
            return Json(true);
        }

        public ViewResult PublisherDetail(int id)
        {
            var publisherModel = _publisherApp.GetPublisherById(id);
            return View("PublisherDetail", PublisherDetailViewModel.FromModel(publisherModel));
        }

        [HttpPost]
        public JsonResult PublisherSave(PublisherViewModel vm)
        {
            if (ModelState.IsValid)
                _publisherApp.WritePublisher(vm.ToModel());

            return Json(ValidationJsonModel.FromModelStateDictionary(ModelState));
        }

        [HttpPost]
        public JsonResult PublisherSearch(FlexigridJsonModel.Request vm)
        {
            FlexigridJsonModel.Response model = _publisherApp.GetPublishers(vm);
            return Json(model);
        }

        private readonly IPublisherApp _publisherApp;
    }
}
